package io.seata.sample.service;

import io.seata.sample.dao.AccountDao;
import io.seata.sample.feign.OrderApi;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author IT云清
 */
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService{

    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServiceImpl.class);
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private OrderApi orderApi;

    /**
     * 扣减账户余额
     * @param userId 用户id
     * @param money 金额
     * @param type
     */
    @Override
    public void decrease(Long userId, BigDecimal money, Integer type) {
        LOGGER.info("------->type: {}", type);

        LOGGER.info("------->扣减账户开始account中");
        accountDao.decrease(userId,money);
        LOGGER.info("------->扣减账户结束account中");

        //模拟超时异常，全局事务回滚
        if (type==4){
            try {
            LOGGER.info("------->模拟超时异常，全局事务回滚 sleep 30s......");
                Thread.sleep(30*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        if (type==5){
            throw new NullPointerException("account 扣减账户之后本地报错");
        }

        //修改订单状态，此调用会导致调用成环
        LOGGER.info("调用 修改订单状态开始");
        String mes = orderApi.update(userId, money.multiply(new BigDecimal("0.09")),0, type);
        LOGGER.info("调用 修改订单状态结束：{}",mes);

        if (type==7){
            throw new NullPointerException("调用 修改订单状态之后本地报错");
        }

    }


}
